package com.itheima.health.service.impl;

import com.itheima.health.common.RedisConst;
import com.itheima.health.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendValidateCode(String validateCodeType, String phone) {
        log.info("[短信-发送验证码]type:{},phone:{}", validateCodeType, phone);
        //生成验证码(1000~9999)
        int code = (int) (1000 + new SecureRandom().nextDouble() * 8999);
        log.info("[短信发送验证码]code:{}", code);
        String redisKey = RedisConst.VALIDATE_CODE_PREFIX + validateCodeType + ":" + phone;
        log.info("redisKey:{},code:{}", redisKey, code);
        redisTemplate.boundValueOps(redisKey).set(String.valueOf(code), 5 * 60L, TimeUnit.MINUTES);
    }

    @Override
    public boolean checkValidateCode(String validateCodeType, String phone, String code) {
        String redisKey = RedisConst.VALIDATE_CODE_PREFIX + validateCodeType + ":" + phone;
        String expectVal = (String) redisTemplate.boundValueOps(redisKey).get();
        if (!StringUtils.isEmpty(expectVal) && expectVal.equals(code)) {
            //如果匹配则删除redis并返回true
            redisTemplate.delete(redisKey);
            return true;
        } else {

            return false;
        }
    }
}

